﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

public class Player : PlayerBase
{
    /// <summary>
    /// 控制器类名
    /// </summary>
    public string ControllerClassName;

    private ControllerBase _controller = null;

    private PlayerData _playerData;

    private Coroutine _talkCor = null;

    public override void Start()
    {
        if (!string.IsNullOrEmpty(ControllerClassName))
        {
            Assembly ass = Assembly.GetExecutingAssembly();

            Type t = ass.GetType(ControllerClassName);
            var controller = (ControllerBase)Activator.CreateInstance(t);
            SetController(controller);
        }

        base.Start();

        GetComponentInChildren<TextMesh>().text = _playerData.Name;
        gameObject.name = _playerData.Name;

        GetComponent<SpriteRenderer>().sprite = ResourceManager.Instance.Load<Sprite>(_playerData.BaseImage);
        transform.Find("gun/gunsprite").GetComponent<SpriteRenderer>().sprite = ResourceManager.Instance.Load<Sprite>(_playerData.GunImage);
        transform.Find("TalkText").gameObject.SetActive(false);
        _controller.Start();
    }

    private void SetController(ControllerBase controller)
    {
        _controller = controller;
        _playerData = _controller.GetPlayerData();
        _controller.SetAction(GetComponent<PlayerObject>(), GetComponent<PlayerObject>(), Move, MoveTo, Turn, TurnTo, Stop, Fire, StopTurn,
            CeaseFire, Talk);
    }

    public override void OnCrashWall()
    {
        _controller.OnCrashWall();
    }

    public override void OnCrashOthers(Vector3 othersPosition, float othersSpeed)
    {
        _controller.OnCrashOthers(othersPosition, othersSpeed);
    }

    public override void OnHitted(float bulletAngle, int damage)
    {
        base.OnHitted(bulletAngle, damage);
        _controller.OnHitted(bulletAngle);
    }

    public override void OnScanOthers(ScanOthersData scanOthersData)
    {
        _controller.OnScanOthers(scanOthersData);
    }

    public override void OnScaned(float angle)
    {
        _controller.OnScaned(angle);
    }

    public override void FixedUpdate()
    {
        base.FixedUpdate();
        _controller.Update();
    }

    public void Talk(string text, float time)
    {
        if (_talkCor != null)
        {
            StopCoroutine(_talkCor);
        }
        _talkCor = StartCoroutine(TalkAction(text, time));
    }

    private IEnumerator TalkAction(string text, float time)
    {
        transform.Find("TalkText").gameObject.SetActive(true);
        transform.Find("TalkText").GetComponent<TextMesh>().text = text;
        yield return new WaitForSeconds(time);
        transform.Find("TalkText").gameObject.SetActive(false);
    }
}